<?php
namespace admin;
use models\BaseDao;
use lmonkey\CatTree as CT;
class Category extends Admin{
    public function  __construct(){
        parent::__construct();
        $this->assign('menumark','category');
        $db = new BaseDao();

        // 获取全部商品分类,按照ord排序
        $data = $db->select('category',['id','catname','pid','ord']);

        $tree = CT::getList($data);
        
        // 将数据全部分给模板
        $this->assign('cats',$tree);
    }
/**
 * 商品分类列表页面
 */
    function index(){
  
        //标题    
        $this->assign('title','商品分类');
        // 导入模板
        $this->display('category/index');
    }
    function add(){
        // 如果$_POST['do_submit]存在,说明是添加动作
        if(isset($_POST['do_submit'])){
            $db = new BaseDao();
            unset($_POST['do_submit']);
            if($db->insert('category',$_POST)){
                $this->success('/admin/category','添加ok');
            }else{
                $this->error('/admin/category/add','添加fail');
            }
        }
        //标题    
        $this->assign('title','添加商品分类');
        $this->display('category/add');

    }
    function mod($id){
        $db = new BaseDao();

        $this->assign('childs',$_GET['childs']);//危险操作,正式项目要从数据库获取参数
        $this->assign($db->get('category','*',['id'=>$id]));
        $this->assign('title',"修改商品分类");
        $this->display('category/mod');
    }
    function doupdate(){
        $id = $_POST['id'];
        unset($_POST['id']);

        $_POST['childs'] .= ",".$id; 

        if(in_array($_POST['pid'],explode(",",$_POST['childs']))){
            $this->error('/admin/category/mod/'.$id,'不能将分类修改到自己或者自己的子类中');
            exit;
        }

        $db = new BaseDao();
        unset($_POST['childs']);

        if($db->update('category',$_POST,['id'=>$id])){
            $this->success('/admin/category','修改ok');
        }else{
            $this->error('/admin/category/mod/'.$id,'修改fail');
        }
    }
    function del($id){
       
        if($_GET['childs'] != ''){
            $this->error('/admin/category','不能删除非空分类');
            exit;
        }
        $db = new BaseDao();
        if($db->delete('category',['id'=>$id])){
            $this->success('/admin/category','删除ok');
        }else{
            $this->error('/admin/category','删除fail');
        }
    }
    function order(){
        $db = new BaseDao();
        $num = 0;
        foreach($_POST['ord'] as $id=>$ord){
            
            $num += $db->update('category',['ord'=>$ord],['id'=>$id]);
        }
        if($num > 0){
            $this->success('/admin/category','排序ok');
        }else{
            $this->success('/admin/category','排序fail');
        }
    }
}